from django.db import models
from frame_server.model import BaseModel
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager

'''管理类'''
class UserManager(BaseUserManager):                                   
    def _create_user(self,**kwargs):
        account = kwargs.get('account')
        name = kwargs.get('name')
        password = kwargs.get('password')
        if not account:
            raise ValueError("请输入账号")
        if not name:
            raise ValueError("请输入昵称")
        if not password:
            raise ValueError("请输入密码")
        user = self.model(**kwargs)                       # 创建用户实例实例
        user.set_password(password)                       # 设置密文密码
        user.save()
        return user
    
    def create_user(self,**kwargs):              # 重写创建普通用户方法
        return self._create_user(**kwargs)
    
    def create_superuser(self,**kwargs):         # 重写创建超级用户方法
        return self._create_user(**kwargs)

'''用户'''
class User(BaseModel, AbstractBaseUser):
    account = models.CharField(unique=True, max_length=20, verbose_name="登陆账号")
    password = models.CharField(max_length=128, verbose_name="登陆密码")
    avatar = models.CharField(max_length=5000,null=True,blank=True, verbose_name="头像")
    name = models.CharField(unique=True, max_length=255,null=True,blank=True, verbose_name="昵称")
    phone = models.CharField(unique=True, max_length=255,null=True,blank=True, verbose_name="手机号")
    is_active = models.SmallIntegerField(default=1, null=True, blank=True, verbose_name="用户状态，0封禁，1未封禁")
    USERNAME_FIELD = 'account'
    REQUIRED_FIELDS = ["name"]
    objects = UserManager()
    
    def __str__(self):
        return self.account
    def has_perm(self, perm, obj=None):
        '''重写内置权限控制，不使用内置权限控制'''
        return True
    def has_module_perms(self, app_label):
        '''重写内置权限控制，不使用内置权限控制'''
        return True
    @property
    def is_staff(self):
        '''重写，永远返回True'''
        return True

    # 获取关联角色id，逗号分隔字符串
    @property
    def roleId(self):
        ids = [str(id) for id in self.userrole_set.only('role_id').values_list('role_id',flat=True)]
        return ','.join(ids)
    
    # 获取关联角色名，逗号分隔字符串
    @property
    def roleName(self):
        return ','.join(self.userrole_set.only('role').values_list('role__roleName',flat=True))

    # 获取关联角色别名，逗号分隔字符串
    @property
    def roleAlias(self):
        return ','.join(self.userrole_set.only('role').values_list('role__roleAlias',flat=True))

    # 获取关联部门id，逗号分隔字符串
    @property
    def deptId(self):
        ids = [str(id) for id in self.userdept_set.values_list('dept__id',flat=True)]
        return ','.join(ids)
    
    # 获取关联部门名，逗号分隔字符串
    @property
    def deptName(self):
        return ','.join(self.userdept_set.only('dept').values_list('dept__deptName',flat=True))
    
    class Meta:
        db_table = 'system_user'
        ordering = ['-createTime']